/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core;

import org.netbeans.modules.tfsnb.core.tabs.TFSConnectionExplorerTopComponent;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class TFSConnectionNode extends AbstractNode {

    private final String CONNECTION_ICON_URL = "org/netbeans/modules/tfsnb/core/TeamFoundationServer.gif";
    
    private static ConnectionSettings connectionSettings;
    private static final Logger LOG = Logger.getLogger(TFSConnectionNode.class.getName());
    
    private final Action[] CONNECTED_ACTIONS = new Action[]{            
            new DisconnectAction(),
//            new MapWorkspacesAction(),
            new OpenAction(),
            new DeleteAction(),
            new EditAction()
        };
    private final Action[] DISCONNECTED_ACTIONS = new Action[]{
            new ConnectAction(),            
            new DeleteAction(),
            new EditAction()
        };
    
    private static final ConnectionService connectionService;
    
    static {
        connectionService = new ConnectionService();
    }
       
    public TFSConnectionNode(final ConnectionSettings connectionSettings) {
        super(Children.LEAF);
        this.connectionSettings = connectionSettings;
        setName(connectionSettings.getName());
    }

    @Override
    public Image getIcon(int type) {        
        return ImageUtilities.loadImage(CONNECTION_ICON_URL);
    }
    
    @Override
    public Action[] getActions(boolean context) {
        boolean connected = connectionService.isConnected(connectionSettings);
        return connected ? CONNECTED_ACTIONS : DISCONNECTED_ACTIONS;
    }
    
    @Override
    public Action getPreferredAction() {
        final String message = NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_ProgressBarConnectingToTFS");
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RequestProcessor.getDefault().post(new Runnable() {

                    @Override
                    public void run() {
                        final ProgressHandle progress = ProgressHandleFactory.createHandle(message);
                        progress.start();
                        openTopComponent();
                        progress.finish();

                    }
                });
            }
        };
    }
    
    private void openTopComponent() {
        //TFSConnectionExplorerTopComponent vtp = (TFSConnectionExplorerTopComponent) WindowManager.getDefault().findTopComponent("TFSConnectionExplorerTopComponent");
        boolean connected = connectionService.isConnected(connectionSettings);
        if(!connected) {
            connectionService.connect(connectionSettings);
        }
        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TFSConnectionExplorerTopComponent vtp = new TFSConnectionExplorerTopComponent();
                vtp.setConnectionSettings(connectionSettings);
                vtp.addComponents();
                vtp.open();
                vtp.requestActive();
            }
        });
    }
    
    private class DeleteAction extends AbstractAction {

        public DeleteAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_DeleteConnectionAction"));
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            NotifyDescriptor d = new NotifyDescriptor.Confirmation(
                    NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_DeleteConnectionConfirmationMessage", connectionSettings.getName()),
                    NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_DeleteConnectionConfirmationDialogTitle"),
                    NotifyDescriptor.OK_CANCEL_OPTION);
            if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.OK_OPTION) {
                connectionService.delete(connectionSettings);                
            }
        }
        
    }
    
    private class EditAction extends AbstractAction {

        public EditAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_EditConnectionAction"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            AddTFSConnectionPanel panel = new AddTFSConnectionPanel(connectionSettings);
            DialogDescriptor dd = new DialogDescriptor(panel, NbBundle.getMessage(TFSRootNode.class, "TFSConnectionNode.LBL_EditConnection"));
            DialogDisplayer.getDefault().notify(dd);
            if(dd.getValue() == DialogDescriptor.OK_OPTION) {
                panel.okButtonPressed();
            } 
        }
        
    }
    
    private class ConnectAction extends AbstractAction {

        public ConnectAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_ConnectConnectionAction"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            connectionService.connect(connectionSettings);
        }
        
    }
    
    private class DisconnectAction extends AbstractAction {

        public DisconnectAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_DisconnectConnectionAction"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            connectionService.disconnect(connectionSettings);
        }
        
    }
    
    private class MapWorkspacesAction extends AbstractAction {

        public MapWorkspacesAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_MapWorkspacesConnectionAction"));
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
//            connectionService.mapWorkspaces(connectionSettings);
            AddExistingTeamProjectPanel panel = new AddExistingTeamProjectPanel(connectionSettings);
            DialogDescriptor dd = new DialogDescriptor(panel, NbBundle.getMessage(TFSRootNode.class, "TFSConnectionNode.LBL_AddExistingTeamProjectPanelTitle"));
            DialogDisplayer.getDefault().notify(dd);
            if(dd.getValue() == DialogDescriptor.OK_OPTION) {
                panel.okButtonPressed();
            } 
        };
        
        
    }

    private class OpenAction extends AbstractAction {

        public OpenAction() {
            super(NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_OpenAction"));
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            final String message = NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_ProgressBarConnectingToTFS");
            RequestProcessor.getDefault().post(new Runnable() {
                
                @Override
                public void run() {
                    final ProgressHandle progress = ProgressHandleFactory.createHandle(message);          
                    progress.start();                    
                    openTopComponent();                    
                    progress.finish();
                    
                }
            });
        }
        
    }
        
}
